package com.huarun.module.user.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huarun.common.BaseController;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.Constant;
import com.huarun.common.util.HttpUtil;
import com.huarun.common.util.MyException;
import com.huarun.common.util.PropertyUtil;
import com.huarun.common.util.ResultCodeEnum;
import com.huarun.common.util.ResultCodeValue;
import com.huarun.common.util.SpringUtils;
import com.huarun.common.util.StringUtils;
import com.huarun.common.util.TokenUtil;
import com.huarun.module.sys.bean.Project;
import com.huarun.module.sys.bean.Subject;
import com.huarun.module.sys.service.IProjectService;
import com.huarun.module.sys.service.ISubjectService;
import com.huarun.module.sys.util.UserInfoUtil;
import com.huarun.module.user.bean.User;
import com.huarun.module.user.service.IUserService;
import com.huarun.module.user.util.LesseeInfoUtil;
import com.huarun.module.webapi.IChunSunServiceApi;
import com.huarun.redis.RedisKeyPrefix;
import com.huarun.redis.RedisUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 用户模块
 * 
 * @author eva
 *
 */
@Controller
@RequestMapping("/wx/user")
@Api(description = "用户")
public class UserController extends BaseController {

	@Resource
	private IUserService userService;
	@Resource
	private ISubjectService subjectService;
	@Resource
	private IProjectService projectService;
	@Resource
	private IChunSunServiceApi chunSunService;

	private RedisUtils redis = null;

	@ApiOperation(value = "切换项目", notes = "切换项目")
	@RequestMapping(value = "/updateProject", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<User> selectProject(HttpServletRequest request) {
		try {
			return userService.saveUserInfo(request);
		} catch (Exception e) {
			e.printStackTrace();
			throw new MyException(ResultCodeValue.R_USERINFO_IS_NULL, "系统异常，请联系管理员");
		}
	}

	@ApiOperation(value = "查询用户权限下的项目信息", notes = "查询用户权限下的项目信息")
	@RequestMapping(value = "/findProjectList", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<List<Project>> findProjectList(HttpServletRequest request,
			@RequestParam String TelPhone) throws Exception {

		ResponseMessage<List<Project>> msg = new ResponseMessage<>();
		Map<String, Object> map = new HashMap<>();
		String openId = request.getHeader("openId");
		// 是否要验证openId
		map.put("openId", openId);
		map.put("accountNo", TelPhone);
		User user = userService.getUserByParams(map);
		if (null != user) {
			Map<String, Object> proMap = new HashMap<>();
			proMap.put("source", user.getSource());
			msg.setData(projectService.getProjectByParams(proMap));
		} else {
			msg.setData(projectService.getProjectByParams(null));
		}

		msg.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		return msg;
	}

	@ApiOperation(value = "查询管理员下面有几个子管理员/查询子管理员", notes = "查询管理员下面有几个子管理员/查询子管理员")
	@RequestMapping(value = "/getLesseeInfo", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<JSONObject> getLesseeInfo(HttpServletRequest request,
			@RequestParam String TelPhone) throws Exception {
		ResponseMessage<JSONObject> msg = new ResponseMessage<JSONObject>();
		// String phone=(String)params.get("TelPhone");
		// 先查找这个人的身份。如果是管理或子管理直接查找，如果是一般租户则去查找公司名称
//		Map<String, Object> param = new HashMap<>();
//		param.put("wxPhone", TelPhone);
//		User u = userService.getUserByParams(param);
//		String info = null;
//		if (null != u && u.getAdmin() == 3) {
//			info = LesseeInfoUtil.getTenantInfoByDeptNameAndProId(request, URLEncoder.encode(u.getDeptName(), "UTF-8"));
//		} else {
			
//		}
		String info	= null;
		if(StringUtils.isNotBlank(TelPhone)) {
			info = LesseeInfoUtil.getTenantInfoByTelAndProId(request, TelPhone);
		}
		String openId = request.getHeader("openId");
		if (openId == null) {
			throw new MyException(ResultCodeValue.R_SESSION_KEY_IS_NULL, "请求的openId为空，请重新获取用户数据");
		}
		if (null != info) {
			JSONObject imisObj = JSONObject.parseObject(info);
			String errorCode = imisObj.getString("ErrorCode");
			if (null != errorCode && "0".equals(errorCode)) {
				msg.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
				msg.setData(imisObj);
			} else {
				msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, imisObj.getString("ErrorMessage"));
			}
		} else {
			msg.setData(null);
			msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
		}
		return msg;
	}

	@ApiOperation(value = "新增子管理员", notes = "新增子管理员")
	@RequestMapping(value = "/saveLesseeChild", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage<JSONObject> saveLesseeChild(HttpServletRequest request,
			@RequestBody Map<String, Object> params) throws Exception {
		ResponseMessage<JSONObject> msg = new ResponseMessage<JSONObject>();
		long time = System.currentTimeMillis();
		Map<String, Object> huaRunParm = new HashMap<>();
		huaRunParm.put("ProjectGuid", request.getHeader("projectId"));
		huaRunParm.put("LesseeRowGuid", params.get("LesseeRowGuid"));
		String telphone = (String) params.get("TelPhone");
		String result = LesseeInfoUtil.getTenantInfoByTelAndProId(request, telphone);
		JSONObject imis = JSONObject.parseObject(result);
		String error = imis.getString("ErrorCode");

		if ("0".equals(error)) {
			User u1 = LesseeInfoUtil.formartLesseeinfo2(result, telphone);
			if (null != u1) {
				msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, "该管理员已经存在");
				return msg;
			}
		}
		//判断是否是属于同一个租户下的普通用户 by mengsg
		
		boolean isInclude = false;
		Map<String, Object> map1 = new HashMap<>();
		map1.put("openId", request.getHeader("openId"));
		User dbUser = userService.getUserByParams(map1);
		if(null != dbUser) {
			String deptName = dbUser.getDeptName();
			//判断是否做此操作的用户所在单位与添加的租户所在单位是否一致
			//春笋
//			if(PropertyUtil.getProperty("chunsun_project_id").equals(request.getHeader("projectId"))) {
//				Map<String, Object> chunSunMap = chunSunService.chunsunGetEmployee(telphone);
//				if (null != chunSunMap && chunSunMap.size() > 0) {
//					if(deptName.equals((String) chunSunMap.get("companyName"))) {
//						isInclude = true;
//					}
//				}
//			}else {//BCD
//
//			}
			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("department", deptName);
			List<Subject> subjectList = subjectService.findList(map2);
			if(null != subjectList && subjectList.size()>0) {
				for (Subject subject : subjectList) {
					if(telphone.equals(subject.getPhone())) {
						isInclude = true;
					}
				}
			}
		}else {
			msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, "系统错误，请重新登录");
			return msg;
		}
		if(!isInclude) {
			msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, "添加的手机号不属于当前单位用户");
			return msg;
		}
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("UserName", params.get("UserName"));
		map.put("TelPhone", params.get("TelPhone"));
		list.add(map);
		huaRunParm.put("ChildInfo", JSON.toJSONString(list));
		String url = Constant.ADD_LESSEE_CHILDREN_INFO;
//		String token = TokenUtil.createToken(url, time, huaRunParm);
		Map<String,Object> tokenMap=TokenUtil.createToken(url, time, huaRunParm);
		String token = tokenMap.get("token").toString();
		url = url + "?token=" + token;
		huaRunParm.put("appkey", Constant.MANAGE_APPKEY);
		huaRunParm.put("time", time);
		huaRunParm.put("ChildInfo", list);
		String json = JSON.toJSONString(huaRunParm);
		System.out.println("json:" + json);
		String resultStr;
		try {
//			resultStr = HttpUtil.postGeneralUrl(Constant.BASE_URL + url, "application/json,text/json", json, "UTF-8");
			resultStr = HttpUtil.postGeneralUrl(Constant.BASE_URL + url, "application/json,text/json", tokenMap.get("parms").toString(), "UTF-8");
			if (null != resultStr) {
				JSONObject imisObj = JSONObject.parseObject(resultStr);
				// JSONObject data = imisObj.getJSONObject("Data");
				// System.out.println(data.toString());
				String errorCode = imisObj.getString("ErrorCode");
				if (null != errorCode && "0".equals(errorCode)) {
					msg.setData(imisObj);
					msg.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
					Map<String, Object> param = new HashMap<>();
					param.put("wxPhone", telphone);
					User user1 = userService.getUserByParams(param);
					if (null != user1) {
						userService.delete(user1.getId());
					}
				} else {
					msg.setData(imisObj.getJSONObject("Data"));
					msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, imisObj.getString("ErrorMessage"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
		}
		return msg;
	}

	@ApiOperation(value = "修改子管理员", notes = "修改子管理员")
	@RequestMapping(value = "/editLesseeChild", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage<String> editLesseeChild(HttpServletRequest request, @RequestBody Map<String, Object> params)
			throws Exception {
		ResponseMessage<String> msg = new ResponseMessage<String>();
		long time = System.currentTimeMillis();
		params.put("ProjectGuid", request.getHeader("projectId"));
		// params.put("LesseeRowGuid",
		// "6d5bd30a-d74d-45c4-9037-db332547aa6e");//新建为黄小姐的子用户
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("RowGuid", params.get("RowGuid"));
		map.put("UserName", params.get("UserName"));
		map.put("TelPhone", params.get("TelPhone"));
		list.add(map);
		params.put("ChildInfo", JSON.toJSONString(list));
		String url = Constant.EDIT_LESSEE_CHILDREN_INFO;
//		String token = TokenUtil.createToken(url, time, params);
		Map<String,Object> tokenMap=TokenUtil.createToken(url, time, params);
		String token = tokenMap.get("token").toString();
		url = url + "?token=" + token;
		params.put("appkey", Constant.MANAGE_APPKEY);
		params.put("time", time);
		params.put("ChildInfo", list);
		String json = JSON.toJSONString(params);
		System.out.println("json:" + json);
		System.out.println("url===========================:" + url);
		String resultStr;
		try {
//			resultStr = HttpUtil.postGeneralUrl(Constant.BASE_URL + url, "application/json,text/json", json, "UTF-8");
			resultStr = HttpUtil.postGeneralUrl(Constant.BASE_URL + url, "application/json,text/json", tokenMap.get("parms").toString(), "UTF-8");
			if (null != resultStr) {
				JSONObject imisObj = JSONObject.parseObject(resultStr);
				JSONObject data = imisObj.getJSONObject("Data");
				System.out.println(data.toString());
				String errorCode = imisObj.getString("ErrorCode");
				if (null != errorCode && "0".equals(errorCode)) {
					// msg.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
					msg.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ""); // 应常俊峰要求成功后返回“”
				} else {
					msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, imisObj.getString("ErrorMessage"));
				}
			} else {
				msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
		}
		return msg;
	}

	@ApiOperation(value = "删除子管理员", notes = "删除子管理员")
	@RequestMapping(value = "/delLesseeChild", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<String> delLesseeChild(HttpServletRequest request,
			@RequestParam(required = true) String RowGuid) throws Exception {
		ResponseMessage<String> msg = new ResponseMessage<String>();
		String info = LesseeInfoUtil.delLesseeChild(request, RowGuid);
		if (null != info) {
			JSONObject imisObj = JSONObject.parseObject(info);
			String errorCode = imisObj.getString("ErrorCode");
			if (null != errorCode && "0".equals(errorCode)) {
				msg.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
				Map<String, Object> params = new HashMap<>();
				params.put("synId", RowGuid);
				User user = userService.getUserByParams(params);
				if (null != user) {
					userService.delete(user.getId());
				}
			} else {
				msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, imisObj.getString("ErrorMessage"));
			}
		} else {
			msg.setCodeAndMsg(ResultCodeEnum.ERROR.code, "删除不成功");
		}
		return msg;
	}

	@ApiOperation(value = "获取租客详情", notes = "获取租客详情")
	@RequestMapping(value = "/getTenantInfo", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<Map<String, Object>> getTenantInfo(HttpServletRequest request, Map<String, Object> params) {
		ResponseMessage<Map<String, Object>> msg = new ResponseMessage<Map<String, Object>>();
		String mobile = (String) params.get("mobile");
		String resultStr = LesseeInfoUtil.getTenantInfoByTelAndProId(request, mobile);
		if (null != resultStr) {
			JSONObject imisObj = JSONObject.parseObject(resultStr);
			JSONObject data = imisObj.getJSONObject("Data");
			System.out.println(data.toString());
			String errorCode = imisObj.getString("ErrorCode");
			if (null != errorCode && "0".equals(errorCode)) {
				JSONArray lesseeInfo = data.getJSONArray("LesseeInfo");
				String lessee = lesseeInfo.get(0).toString();
				msg.setData(StringUtils.jasonConvertMap(lessee));
				msg.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			}
		}
		return msg;
	}

	@ApiOperation(value = "获取租客房间号", notes = "获取租客房间号")
	@RequestMapping(value = "/getTenantInfoByTel", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<Object> getTenantInfoByTel(HttpServletRequest request, Map<String, Object> params) {
		long time = System.currentTimeMillis();
		String phone = (String) request.getParameter("phone");
		String projectId = (String) request.getHeader("projectId");

		Map<String, Object> param = new HashMap<>();
		param.put("wxPhone", phone);
		User u = userService.getUserByParams(param);
		String url = null;
		ResponseMessage<Object> rm = new ResponseMessage<Object>();
		try {
			if (null != u && u.getAdmin() == 3) {
				url = Constant.TENANT_INFO_BY_TEL_AND_DEPTNAME + projectId + "/"
						+ URLEncoder.encode(u.getDeptName(), "UTF-8");

			} else {
				url = Constant.TENANT_INFO_BY_TEL_AND_PROID + projectId + "/" + phone;
			}

			// String phone = "18822858373";
			// String url = Constant.TENANT_INFO_BY_TEL_AND_PROID + projectId + "/" + phone;
			String token = TokenUtil.createToken(url, request, time, null);
			url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
			String resultStr = null;

			resultStr = HttpUtil.doGet(Constant.BASE_URL + url);
			JSONObject imisObj = JSONObject.parseObject(resultStr);
			String errorCode = imisObj.getString("ErrorCode");
			if (null != errorCode && "0".equals(errorCode)) {
				JSONObject data = imisObj.getJSONObject("Data");
				rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
				rm.setData(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
		}
		return rm;
	}

}
